import { useState, useEffect, useRef } from 'react'
import { useIsMobile } from '../hooks/useMediaQuery'

/**
 * 懒加载图片组件 - 移动端优化
 */
export default function LazyImage({ 
  src, 
  alt = '', 
  className = '',
  placeholder = null,
  threshold = 0.1,
  rootMargin = '50px',
  ...props 
}) {
  const [isLoaded, setIsLoaded] = useState(false)
  const [isInView, setIsInView] = useState(false)
  const [error, setError] = useState(false)
  const imgRef = useRef(null)
  const isMobile = useIsMobile()

  useEffect(() => {
    // 使用 Intersection Observer 实现懒加载
    if (!imgRef.current) return

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setIsInView(true)
            observer.unobserve(entry.target)
          }
        })
      },
      {
        threshold,
        rootMargin
      }
    )

    observer.observe(imgRef.current)

    return () => {
      if (imgRef.current) {
        observer.unobserve(imgRef.current)
      }
    }
  }, [threshold, rootMargin])

  const handleLoad = () => {
    setIsLoaded(true)
  }

  const handleError = () => {
    setError(true)
  }

  return (
    <div 
      ref={imgRef}
      className={`relative overflow-hidden ${className}`}
      {...props}
    >
      {/* 占位符 */}
      {!isLoaded && !error && (
        <div className="absolute inset-0 bg-gradient-to-br from-gray-800/50 to-gray-700/50 animate-pulse">
          {placeholder || (
            <div className="absolute inset-0 flex items-center justify-center">
              <svg className="w-12 h-12 text-gray-600 animate-pulse" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clipRule="evenodd" />
              </svg>
            </div>
          )}
        </div>
      )}

      {/* 错误状态 */}
      {error && (
        <div className="absolute inset-0 bg-gray-800/50 flex items-center justify-center">
          <div className="text-center">
            <svg className="w-12 h-12 text-gray-500 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p className="text-gray-400 text-sm">图片加载失败</p>
          </div>
        </div>
      )}

      {/* 实际图片 */}
      {isInView && (
        <img
          src={src}
          alt={alt}
          onLoad={handleLoad}
          onError={handleError}
          className={`transition-opacity duration-300 ${
            isLoaded ? 'opacity-100' : 'opacity-0'
          }`}
          loading="lazy"
          decoding="async"
          // 移动端优化：降低图片质量
          {...(isMobile && {
            style: {
              imageRendering: 'auto',
              WebkitOptimizeContrast: 'auto'
            }
          })}
        />
      )}
    </div>
  )
}

/**
 * 背景图片懒加载组件
 */
export function LazyBackgroundImage({ 
  src, 
  children, 
  className = '',
  threshold = 0.1,
  rootMargin = '50px',
  ...props 
}) {
  const [isInView, setIsInView] = useState(false)
  const [isLoaded, setIsLoaded] = useState(false)
  const divRef = useRef(null)

  useEffect(() => {
    if (!divRef.current) return

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setIsInView(true)
            observer.unobserve(entry.target)
          }
        })
      },
      {
        threshold,
        rootMargin
      }
    )

    observer.observe(divRef.current)

    return () => {
      if (divRef.current) {
        observer.unobserve(divRef.current)
      }
    }
  }, [threshold, rootMargin])

  useEffect(() => {
    if (isInView && src) {
      const img = new Image()
      img.onload = () => setIsLoaded(true)
      img.src = src
    }
  }, [isInView, src])

  return (
    <div
      ref={divRef}
      className={`${className} transition-opacity duration-300 ${
        isLoaded ? 'opacity-100' : 'opacity-0'
      }`}
      style={{
        backgroundImage: isLoaded ? `url(${src})` : 'none',
      }}
      {...props}
    >
      {children}
    </div>
  )
}

